<?php

/**
 * 数据库管理类
 * 
 * @package Db
 * @author Chengxuan <chengxuan@leju.sina.com.cn>
 * @version #Id:db.php 2010-4-27 下午06:04:07#
 */
abstract class Cls_Db {
	/**
	 * 数据库前缀
	 * @var string
	 */
	const PRE = 'udc_';
	
	/**
	 * 所使用的驱动
	 * @var string
	 */
	static $driver = 'pdo';
	
	/**
	 * 是否显示错误（多功能数值相加）
	 * 	0	不显示
	 * 	1	将错误写入日志
	 * 	2	将错误显示在页面上
	 * 	4	将错误发送至FirePHP
	 * 	8	追踪错误发送至FirePHP
	 *  16	出错终止
	 * 
	 * @var int
	 */
	static $error = 30;

	/**
	 * 数据库操作对象
	 * @var Cls_db_Base
	 */
	static $db = array();
	
	/**
	 * 返回数据库默认配置
	 * @return array
	 */
	static protected function _default_config()
	{
		return array(
			Cls_Db_Base::CONN_MASTER => array(
				'host'		=> $_SERVER['SINASRV_DB_HOST'],
				'port'		=> $_SERVER['SINASRV_DB_PORT'],
				'username'	=> $_SERVER['SINASRV_DB_USER'],
				'password'	=> $_SERVER['SINASRV_DB_PASS'],
				'database'	=> $_SERVER['SINASRV_DB_NAME'],
			),
			
			Cls_Db_Base::CONN_SLAVE => array(
				'host'		=> $_SERVER['SINASRV_DB_HOST_R'],
				'port'		=> $_SERVER['SINASRV_DB_PORT_R'],
				'username'	=> $_SERVER['SINASRV_DB_USER_R'],
				'password'	=> $_SERVER['SINASRV_DB_PASS_R'],
				'database'	=> $_SERVER['SINASRV_DB_NAME_R'],
			),			
		);
	}
	
	/**
	 * 取得数据库操作对象（Database）
	 * @param string $id	唯一数据标识
	 * @return Cls_Db_Base
	 */
	static public function D($id='_default_') {
		if(!isset(self::$db[$id]))
		{
			if($id !== '_default_') return false;
			return self::add($id, self::_default_config());
		}

		return self::$db[$id];
	}
	
	/**
	 * 新增一数据连接标识
	 * 
	 * $conf 格式示例
	 * <code>
	 *  array(
	 * 		Cls_Db_Base::CONN_MASTER => array(
	 *			'host'		=> $_SERVER['SINASRV_DB_HOST'],
	 *			'port'		=> $_SERVER['SINASRV_DB_PORT'],
	 *			'username'	=> $_SERVER['SINASRV_DB_USER'],
	 *			'password'	=> $_SERVER['SINASRV_DB_PASS'],
	 *			'database'	=> $_SERVER['SINASRV_DB_NAME'],
	 *		),
	 *	
	 *		Cls_Db_Base::CONN_SLAVE => array(
	 *			'host'		=> $_SERVER['SINASRV_DB_HOST_R'],
	 *			'port'		=> $_SERVER['SINASRV_DB_PORT_R'],
	 *			'username'	=> $_SERVER['SINASRV_DB_USER_R'],
	 *			'password'	=> $_SERVER['SINASRV_DB_PASS_R'],
	 *			'database'	=> $_SERVER['SINASRV_DB_NAME_R'],
	 * 		)
	 *	)
	 * </code>
	 * 
	 * @param string	$id				唯一数据标识
	 * @param array		$conf			数据库配置信息
	 * @param string	$driver			所使用的驱动
	 * @param int		$display_errors	错误级别
	 * @return Cls_Db_Base
	 */
	static public function add($id, $conf, $driver='', $display_errors=false)
	{
		!$driver && $driver = self::$driver;
		$display_errors === false && $display_errors = self::$error;
		
		$class = 'Cls_Db_' . self::$driver;
		self::$db[$id] = new $class($conf);
		self::$db[$id]->display_errors = self::$error;
		return self::$db[$id];
	}
}

